<template>
  <PageLayout full safe-area="none" :page-style="pageStyle" class="my-index">
    <template #header>
      <HeaderLayout>
        <view></view>
        <view>{{ $t('Navigator.Bottom.My.Text') }}</view>
        <view></view>
      </HeaderLayout>
    </template>

    <!-- 用户信息 -->
    <TrackButton track-id="Navigator.My.ArrowRight.Icon">
      <view class="user-msg-box" @click="getUserProfile">
        <view class="user-msg">
          <view class="user-phone">
            <image v-if="avatarUrl" class="photo-box" :src="avatarUrl" @error="avatarUrl = ''"></image>
            <image v-else-if="!avatarUrl" class="photo-box" src="/static/ic_header.png"></image>
          </view>
          <view v-if="authStore.isLogin" class="user-name">{{ userName }}</view>
          <view v-else class="user-name">点击登录</view>
        </view>
        <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
      </view>
    </TrackButton>
    <!-- banner -->
    <view class="my-banner" @click="jumpWeb(bannerUrl)" v-if="isShowBannerFnc">
      <image class="banner-img" :src="bannerImg" mode="aspectFix"></image>
      <image
        class="banner-close"
        mode="aspectFix"
        src="@/static/Close.png"
        @click.stop="closeBanner"
        v-if="isShowBannerClose === 1"
      ></image>
    </view>
    <!-- 设置 -->
    <TrackButton :track-id="settingTrackId">
      <view class="my-set-box" :style="`margin-top:${isShowBanner ? '16rpx' : '32rpx'}`">
        <view class="set-box" @click="goGeneralSetting">
          <view class="set-dec">
            <image class="set-icon" :src="'/static/my/Setting.png'"></image>
            <view class="set-text">{{ $t('Navigator.My.GeneralSetting.Text') }}</view>
          </view>
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
        <view class="set-box" @click="goToAfterService">
          <view class="set-dec">
            <image class="set-icon" :src="'/static/my/Afterservice.png'"></image>
            <view class="set-text">{{ $t('Navigator.My.AfterService.Text') }}</view>
          </view>
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
        <view class="set-box" @click="settingTrackId = 'Navigator.My.SmartService.Text'">
          <button class="remove-btn-border set-box" open-type="contact" plain="true" hover-class="none">
            <view class="set-dec">
              <image class="set-icon" :src="'/static/my/IntelligentCS.png'"></image>
              <view class="set-text">{{ $t('Navigator.My.SmartService.Text') }}</view>
            </view>
            <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
          </button>
        </view>
        <!--我的优惠券-->
        <view class="set-box" @click="goToMyCoupon">
          <view class="set-dec">
            <image class="set-icon" :src="'/static/my/Coupon.png'"></image>
            <view class="set-text">{{ $t('Navigator.My.MyCoupon.Text') }}</view>
          </view>
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
        <view class="set-box" @click="settingTrackId = 'Navigator.My.SuggestedFeedback.Text'">
          <button class="remove-btn-border set-box" open-type="feedback" plain="true" hover-class="none">
            <view class="set-dec">
              <image class="set-icon" :src="'/static/my/Feedback.png'"></image>
              <view class="set-text">{{ $t('Navigator.My.SuggestedFeedback.Text') }}</view>
            </view>
            <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
          </button>
        </view>
        <view class="set-box" @click="goToAbout">
          <view class="set-dec">
            <image class="set-icon" src="/static/my/Info.png"></image>
            <view class="set-text">{{ $t('Navigator.My.AboutApp.Text') }}</view>
          </view>
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
      </view>
    </TrackButton>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import { useEnvStore } from '@/store/env'
import { onLoad, onShow } from '@dcloudio/uni-app'
import loginHelper from '@/pluginHelper/login'
import { useAuthStore } from '@/store/auth'
import { getWxDetail } from '@/api/account'
import { TrackType } from '../../../dataReport/tracks'
import { useAccountStore } from '@/store/account'
import { getBannerInfo, jumpBannerWeb } from '@/api/common'

import netconfig from '@/config/netconfig'
const authStore = useAuthStore()
const pageStyle = {
  backgroundColor: '#F4F4F4',
}

// const defaultAvatarUrl =
//   'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

/**
 * Tab组件生命周期
 */
defineExpose({
  onPageLoad,
  onActive,
})
function onPageLoad(query?: Record<string, any>) {}
function onActive() {
  if (authStore.isLogin) {
    getWxDetailFun()
  }
}
/**
 * bannaer跳转
 */
const isShowBanner = ref(false)
const isShowBannerClose = ref(0) //是否可以关闭 0:可关闭 1:不可关闭
const actionType = ref('1') //跳转类型1:微信文章 2:三方小程序appid及跳转路径 3:三方H5链接
const bannerAppId = ref<string | null>(null)
function jumpWeb(option: any) {
  let questionnaireUrl = ''
  let myUrl = ''
  if (actionType.value === '1' || actionType.value === '3') {
    questionnaireUrl = `/pages/webview/webview?url=${bannerUrl.value}`
    myUrl = `pages/webview/webview?url=${bannerUrl.value}`
  } else {
    questionnaireUrl = bannerUrl.value
    myUrl = `pages/navigator/index`
  }
  jumpBannerWeb(questionnaireUrl, myUrl, actionType.value, bannerAppId.value as string, 'My.Banner.Survey.Click')
}
/**
 * 获取banner接口
 */
const bannerImg = ref('')
const bannerUrl = ref('')
const imgUrl = netconfig.ASSETSPRE
async function getBannerList() {
  await getBannerInfo().then((res) => {
    if (res.code === 0) {
      if (res.data && res.data.length > 0) {
        bannerImg.value = `${imgUrl}${res.data[0].imageUrl}`
        bannerUrl.value = res.data[0].landingPage
        actionType.value = res.data[0].actionType
        isShowBannerClose.value = res.data[0].close
        bannerAppId.value = res.data[0].appid
        isShowBanner.value = true
      } else {
        isShowBanner.value = false
      }
    }
  })
}

/**
 * 关闭banner
 */
const isShowBannerFnc = computed(() => {
  return isShowBanner.value && !uni.getStorageSync('bannerClose')
})
async function closeBanner() {
  uni.setStorageSync('bannerClose', true)
  isShowBanner.value = false
}
onShow(() => {
  getUserInfo()
  if (authStore.isLogin) {
    getBannerList()
  }
})

/**
 * 页面状态
 */
let nav = false
let settingTrackId = ref<string>('')
const getProfile = ref(false)
const userName = ref('')
const avatarUrl = ref('')

function getUserInfo() {
  let userProfile = uni.getStorageSync('userProfile')
  if (userProfile && userProfile.userName) {
    userName.value = userProfile.userName
    avatarUrl.value = userProfile.avatarUrl
    getProfile.value = true
    if (userName.value) accountStore.undateOwnerName(userName.value)
  } else {
    userName.value = ''
    avatarUrl.value = ''
    getProfile.value = false
  }
}
/**
 * 获取用户信息和未读信息
 */
const accountStore = useAccountStore()
async function getWxDetailFun() {
  if (authStore.isLogin) {
    try {
      const detailResult = await getWxDetail()
      userName.value = detailResult.data.lastname + detailResult.data.firstname
      uni.setStorage({
        key: 'userProfile',
        data: { userName: userName.value, avatarUrl: getProfile.value ? avatarUrl.value : '' },
      })
      if (userName.value) accountStore.undateOwnerName(userName.value)
    } catch (error) {
      console.error('获取用户信息失败：', error)
    }
  }
}
/**
 * 获取微信用户信息
 */
function getUserProfile() {
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin(undefined, { path: 'pages/navigator/index/index?current=2' })
    return
  }
  if (nav) {
    uni.showToast({
      title: '操作太快，请稍候',
      icon: 'none',
    })
    return
  }
  nav = true
  uni.navigateTo({
    url: `/pages/my/accountSetting/accountSetting?getProfile=${getProfile.value}&nickName=${userName.value}&avatarUrl=${avatarUrl.value}`,
    complete: () => {
      setTimeout(() => {
        nav = false
      }, 1500)
    },
  })
}
/**
 * 跳转通用设置
 */
function goGeneralSetting() {
  settingTrackId.value = 'Navigator.My.GeneralSetting.Text'
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin(undefined, { path: 'pages/my/generalSetting/generalSetting' })
    return
  }
  uni.navigateTo({
    url: '/pages/my/generalSetting/generalSetting',
  })
}

/**
 * 售后服务
 */
function goToAfterService() {
  settingTrackId.value = 'Navigator.My.AfterService.Text'
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin(undefined, { path: 'pages/my/afterService/afterService' })
    return
  }
  uni.navigateTo({
    url: '/pages/my/afterService/afterService',
  })
}

/**
 * 跳转关于
 */
function goToAbout() {
  settingTrackId.value = 'Navigator.My.AboutApp.Text'
  uni.navigateTo({
    url: '/pages/my/about/about',
  })
}

/**
 * 跳转我的优惠券
 */
function goToMyCoupon() {
  settingTrackId.value = 'Navigator.My.MyCoupon.Text'
  if (!authStore.isLogin) {
    loginHelper.noCiamIdLogin(undefined, { path: 'pages/my/myCoupon/myCoupon' })
    return
  }
  uni.navigateTo({
    url: '/pages/my/myCoupon/myCoupon',
  })
}
</script>

<style lang="less">
.my-index {
  // 去除button的原有样式
  .my-banner {
    width: 100%;
    height: 100px;
    background: var(--grey-e-2-e-2-e-2, #e2e2e2);
    margin-top: 16rpx;
    position: relative;
    .banner-img {
      position: absolute;
      width: 100%;
      height: 100%;
    }
    .banner-close {
      position: absolute;
      width: 24rpx;
      height: 24rpx;
      scale: 1.5;
      right: 8rpx;
      top: 8rpx;
    }
  }
  .remove-btn-border {
    width: 100%;
    border: none;
    box-shadow: inherit;
    padding: 0;
    margin: 0;
    color: #000;
  }
  .remove-btn-border::after {
    border: none;
    border-radius: 0;
  }
  .remove-btn-border[plain] {
    border: none;
  }
  .photo-box {
    width: 100%;
    height: 100%;
    background-color: #f4f4f6;
  }
  // 用户信息
  .user-msg-box {
    height: 224rpx;
    padding: 46rpx 32rpx 30rpx;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    overflow: hidden;

    border-bottom: 1rpx solid rgba(233, 233, 237, 1);
    .user-msg {
      display: flex;
      align-items: center;

      .user-phone {
        width: 148rpx;
        height: 148rpx;
        border-radius: 50%;
        margin-right: 32rpx;
        overflow: hidden;
      }
      .user-name {
        width: 460rpx;
        font-weight: 500;
        font-size: 48rpx;
        color: var(--dark-color);
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  // 设置
  .my-set-box {
    background-color: #fff;
    padding: 0 32rpx;
    border-bottom: 1rpx solid rgba(233, 233, 237, 1);
    border-top: 1rpx solid rgba(233, 233, 237, 1);
    .set-box {
      height: 112rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: relative;
      &::after {
        bottom: 0;
        position: absolute;
        content: '';
        display: block;
        width: calc(100% + 32rpx);
        height: 1px;
        background-color: rgba(233, 233, 237, 1);
      }

      .set-dec {
        display: flex;
        align-items: center;
        .set-icon {
          width: 40rpx;
          height: 40rpx;
        }
        .set-text {
          margin-left: 26rpx;
          font-size: 32rpx;
          font-weight: 500;
          color: var(--primary-petrol, #2d3746);
        }
      }
    }
    .set-box:last-of-type {
      border-bottom: none;
      &::after {
        display: none;
      }
    }
  }
  // 箭头
  .arrow-right {
    width: 14rpx;
    height: 24rpx;
  }
}
</style>
